<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>post请求</title>
</head>

<body>
    <form action="">
        <input type="text" name="name" id="">
        <input type="text" name="age" id="">
        <input type="text" name="sex" id="">
        <button>提交</button>
    </form>
    <script>
        const oForm = document.querySelector('form')
        const oName = document.querySelector('[name=name]')
        const oAge = document.querySelector('[name=age]')
        const oSex = document.querySelector('[name=sex]')
        oForm.onsubmit = function () {
            const xhr = new XMLHttpRequest()
            //设置请求头
            
            
            xhr.open('POST', '/adduser')
            xhr.setRequestHeader('Content-Type','application/json;charset=utf-8')//设置发送的请求数据为json类型
            // xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')//设置发送的请求数据为form表单类型
            // xhr.send('name=laoli&age="18"')
            const name=oName.value
            const age=oAge.value
            const sex=oSex.value

            xhr.send(JSON.stringify({name:name,age:age,sex:sex}))
           
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status <= 299) {
                    console.log(xhr.responseText);
                }
            }

            return false
        }
    </script>
</body>

</html>